package com.luguz.util;
import com.luguz.common.HotSearch.HotSearchDao;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.util.*;

/**
 * @author Guz
 * @create 2022-02--28 12:31
 */
public class getHotSearchUtil {


    public static String filterHotType(String type){
        String res = "";
        switch (type){
            case "微博":
                res = "wb";
                break;
            case "知乎":
                res = "zh";
                break;
            case "微信":
                res = "wx";
                break;
            case "百度":
                res = "bd";
                break;
            default:
                res ="";
        }
        return res;
    }

    public static Map<String, ArrayList<HotSearchDao>> getHotSearch(){
        Map<String, ArrayList<HotSearchDao>> hotSearchMap = new HashMap<String, ArrayList<HotSearchDao>>();
        int  dataNumber = 6;
        List<String> strList = Arrays.asList(new String[] { "微博", "知乎", "百度","微信"});
        try {
            String urlStr = "https://tophub.today/";
            final Document doc = Jsoup.connect(urlStr).get();//获取html
            Element trs = doc.getElementById("Sortable");//获取tbody下的所有tr下的html内容
//            System.out.println(trs);
            Elements elementsByClass = trs.getElementsByClass("cc-cd");
            for (Element ele: elementsByClass) {
//                System.out.println(ele);
                String hotSource = ele.getElementsByClass("cc-cd-lb").first().getElementsByTag("span").text();
//              只爬取 "微博", "知乎", "百度"，"微信"的热搜
                if(!strList.contains(hotSource)) continue;
                hotSource = getHotSearchUtil.filterHotType(hotSource);
                Elements a = ele.getElementsByClass("nano-content").first().getElementsByTag("a");
                String date = DateFormat.getDateTimeInstance().format(new Date());
                ArrayList<HotSearchDao> datas= new ArrayList<HotSearchDao>();
                for (int i = 0; i < dataNumber; i++) {
                    Elements data = a.eq(i);
                    String link = data.eq(0).attr("href");
                    String title = data.first().getElementsByClass("t").eq(0).text();
                    String number = data.first().getElementsByClass("e").eq(0).text();
                    datas.add(new HotSearchDao(title,number,link,date));
                }
                hotSearchMap.put(hotSource,datas );
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            return hotSearchMap;
        }
    }

}
